package com.chen.boot.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chen.boot.db.entity.ChatMessage;
import com.chen.boot.db.entity.ClientInfo;
import com.chen.boot.db.entity.ContactsInfo;
import com.chen.boot.db.mapper.ChatMessageMapper;
import com.chen.common.Result;
import com.chen.common.Utils;
import com.chen.im.MessageType;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.time.LocalDateTime;

/**
 * @Description
 * @Author Pengwei
 * @CreatDate 2021/11/14 22:46
 */
@Service
public class ChatMessageService extends ServiceImpl<ChatMessageMapper, ChatMessage> {
    private static RestTemplate restTemplate = new RestTemplate();
    private ParameterizedTypeReference<Result> sendBackType = new ParameterizedTypeReference<Result>() {
    };

    @Value("${server.port}")
    String serverPort;
    @Value("${server.servlet.context-path}")
    String contextPath;

    //发送消息
    public void sendMessage(ContactsInfo contactsInfo, String content, MessageType messageType) {
        if (messageType.equals(MessageType.text)) {
            sendTextMessage(contactsInfo, content);
        }
    }

    //发送文字消息
    private void sendTextMessage(ContactsInfo contactsInfo, String content) {
        //本地入库,获得messageID
        ChatMessage chatMessage = new ChatMessage();
        chatMessage.setId(IdWorker.getId(null));
        chatMessage.setContent(content);
        chatMessage.setCreateTime(LocalDateTime.now());
        chatMessage.setOutBol(true);
        chatMessage.setSendBol(false);
        chatMessage.setMsgFlag(MessageType.text.getFlag());
        chatMessage.setObjClientId(contactsInfo.getId());
        //save(chatMessage);
        //将消息发送给对方
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity request = new HttpEntity<>(chatMessage,headers);
        String url = Utils.format("http://{}:{}{}/receiveText", contactsInfo.getIp(), serverPort, contextPath);
        Result body = restTemplate.exchange(url, HttpMethod.POST, request, sendBackType).getBody();
        //检查成功,增加进联系人列表
        if (body != null && body.isOk()) {
            chatMessage.setSendBol(true);
        }
        save(chatMessage);
    }

    public void receiveTextMessage(ChatMessage chatMessage) {
        chatMessage.setOutBol(false);
        chatMessage.setReadBol(false);
    }
}